<template>
  <a-modal title="完成交车" :visible="visible" width="85vw" unmount-on-close @cancel="close">
    <div class="page-container relative give-car-wrapper" style="position: relative">
      <div class="page-form-block">
        <!-- 统计 -->
        <summary-info :summaryList="summaryLease" />
        <a-divider />
        <summary-info :summaryList="summaryMember">
          <template #memberName>
            {{ memberInfo?.memberName || '-' }}
            <a-button
              size="mini"
              type="primary"
              style="margin-left: 10px"
              v-if="orderDetailGetted && (!memberInfo.driverFrontFileId || !memberInfo.driverReverseFileId)"
              @click="uploadDrivierFn"
            >
              未上传驾驶证
            </a-button>
            <a-button
              size="mini"
              type="primary"
              style="margin-left: 10px"
              v-if="orderDetailGetted && (!memberInfo.idCardFrontFileId || (memberInfo.cardType == 0 && !memberInfo.idCardReverseFileId))"
              @click="uploadIdCardFn"
            >
              未上传身份证明
            </a-button>
          </template>
        </summary-info>
      </div>
      <a-divider />
      <!-- 参考里程/油电量 -->
      <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
        <card title="交车信息" style="margin-top: 20px">
          <box-info :carId="form.carId" style="margin-bottom: 20px" />
          <page-form-row>
            <page-form-item label="出库里程" size="1/3"> {{ outCarMileage || '-' }}公里 </page-form-item>
            <page-form-item label="出库油(电)量" size="2/3"> {{ outCarOil || '-' }} </page-form-item>
          </page-form-row>
          <page-form-row>
            <page-form-item label="交车里程" field="startCarMileage">
              <i-input-number :precision="0" unit="公里" v-model="form.startCarMileage" />
            </page-form-item>
            <page-form-item label="交车油(电)量" field="startCarOil">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.startCarOil" />
            </page-form-item>
            <page-form-item field="giveStaffId" label="交车人">
              {{ workOperatorName || '-' }}
            </page-form-item>
            <page-form-item field="useStartTime" label="交车时间">
              <i-date-picker class="w-full" v-model="form.useStartTime" showTime popup-container=".give-car-wrapper" />
            </page-form-item>
            <page-form-item label="交车备注" size="2/3">
              <i-textarea v-model="form.useStartRemark" />
            </page-form-item>
            <page-form-item label="交车照片" size="1">
              <upload-img v-model="form.fileIds" />
            </page-form-item>
            <page-form-item label="交车视频" size="1" class="mb-0">
              <upload-video v-model="form.giveVideoFileIds" :max="1" />
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
      <!-- 费用信息 -->
      <div class="relative fee-pane-content">
        <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <card toggle :showDivider="false">
            <template #title>交车费</template>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane :orderFeeIndex="index" :disabledOnlineFee="orderInfo.orderSource == 1" />
            </template>
          </card>
        </page-form>
      </div>
    </div>
    <!-- 底部 footer -->
    <!-- <page-form-footer :ok-loading="okLoading" @ok="submitFn" /> -->
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
    </template>
    <!-- 上传驾驶证照片 -->
    <upload-driver-license-modal ref="uploadDriverLicenseModalRef" @ok="uploadSuccessFn" />
    <!-- 上传身份证明照片 -->
    <upload-id-card-modal ref="uploadIdCardModalRef" @ok="uploadIdCardSuccessFn" />
  </a-modal>
</template>
<script setup name="ShortOrderGiveCar">
  import { ref, provide, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'
  import { finishGiveCar } from '@/api/business/workorder'
  import { getLongOrderDetails } from '@/api/order/czsOrder'
  import { getShortOrdrDetails } from '@/api/order/sOrder'
  import feePane from './order-fee/fee-pane.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './order-fee/fee-utils.js'
  import uploadDriverLicenseModal from './upload-driver-license-modal.vue'
  import uploadIdCardModal from '../../longOrder/giveCar/upload-id-card-modal.vue'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import summaryInfo from './summary-info.vue'
  import boxInfo from '../../../components/box-modal.vue'
  import useNavigate from '@/hooks/useNavigate'
  const { navigateBack } = useNavigate()
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'
  const emit = defineEmits(['ok'])
  const userStore = useUserStore()
  const route = useRoute()
  const orderId = ref(null)
  const orderInfo = ref({})
  const memberInfo = ref({})
  const orderDetailGetted = ref(false)
  const visible = ref(false)
  const outCarMileage = ref(null)
  const outCarOil = ref(null)
  const workOperatorName = ref(null)

  const form = ref({
    id: orderId.value,
    useStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  const initForm = () => {
    form.value = {
      id: orderId.value,
      useStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
  }
  // 处理默认值
  const rules = {
    giveStaffId: [{ required: true, message: '请选择交车人' }],
    useStartTime: [{ required: true, message: '请选择交车时间' }],
    startCarMileage: [{ required: true, message: '请输入交车里程' }], // 交车里程
    startCarOil: [{ required: true, message: '请输入交车油(电)量' }], // 交车油(电)量
  }
  const formRef = ref()
  provide('form', form)

  // 上传驾驶证
  const uploadDriverLicenseModalRef = ref()
  const uploadDrivierFn = () => {
    uploadDriverLicenseModalRef.value.open(memberInfo?.value.id, memberInfo?.value.driverFrontFileId, memberInfo?.value.driverReverseFileId)
  }
  // 上传完成
  // 更新驾驶证正反面信息
  const uploadSuccessFn = (info) => {
    memberInfo.value.driverFrontFileId = info.driverFrontFileId
    memberInfo.value.driverReverseFileId = info.driverReverseFileId
  }
  // 上传身份证明
  const uploadIdCardModalRef = ref()
  const uploadIdCardFn = () => {
    uploadIdCardModalRef.value.open(
      memberInfo.value.id,
      memberInfo.value.cardType,
      memberInfo.value.idCardFrontFileId,
      memberInfo.value.idCardReverseFileId
    )
  }
  // 上传完成
  // 更新身份证明正反面信息
  const uploadIdCardSuccessFn = (info) => {
    memberInfo.value.idCardFrontFileId = info.idCardFrontFileId
    memberInfo.value.idCardReverseFileId = info.idCardReverseFileId
  }
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: `${orderInfoVal.startTime} - ${orderInfoVal.endTime}`,
        },
        { label: '租期', value: orderInfoVal.rentDays },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '车型', value: orderInfoVal.originalSiteModelName },
        { label: '交车车型', value: orderInfoVal.carModelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.carLicenseNo }],
    ]
  })

  const summaryMember = computed(() => {
    const memberInfoVal = memberInfo.value
    const orderInfoVal = orderInfo.value
    return [
      orderInfoVal.clientId
        ? [
            { label: '承租人', slotName: 'memberName' },
            { label: '企业名称', value: orderInfoVal.clientName },
            { label: '证件类型', value: memberInfoVal?.cardTypeName },
          ]
        : [
            { label: '承租人', slotName: 'memberName' },
            { label: '证件类型', value: memberInfoVal?.cardTypeName },
          ],
      [
        { label: '联系电话', value: memberInfoVal?.phone },
        { label: '证件号', value: memberInfoVal?.cardNumber },
      ],
    ]
  })

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const defaultStaffId = ref()

  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        let feeFormValue = feeForm.value
        let costInfo = buildCostInfoParam(feeFormValue)
        const param = {
          ...form.value,
          orderFee: costInfo.orderFee[0],
        }
        okLoading.value = true
        finishGiveCar(param)
          .then((res) => {
            console.log(res)
            Message.success(res.message)
            close()
            emit('ok')
          })
          .finally(() => (okLoading.value = false))
      }
    })
  }
  const open = (record) => {
    initForm()
    form.value.giveStaffId = record.workOperatorId //工单负责人id
    form.value.giveStaffName = record.workOperatorName //工单负责人name
    workOperatorName.value = record.workOperatorName // 工单负责人Name

    outCarMileage.value = record.outCarMileage // 出库里程
    outCarOil.value = record.outCarOil // 出库油电量

    visible.value = true
    orderId.value = record.refId
    form.value.id = record.id
    form.value.carId = record.carId
    if (orderId.value) {
      var pageAPI = ''
      if (record.refType == 2) {
        record.refType = 2
        pageAPI = getLongOrderDetails
      } else {
        record.refType = 1
        pageAPI = getShortOrdrDetails
      }
      pageAPI({ id: orderId.value }).then((res) => {
        orderDetailGetted.value = true
        const result = res.result
        orderInfo.value = result.orderInfo
        memberInfo.value = result.memberInfoDto
        // 处理默认值
        // 车务专员 | 当前登录者 id
        defaultStaffId.value = orderInfo.value.giveStaffId || userStore.employeeId
        // 默认交车人
        form.value.giveStaffId = defaultStaffId.value
        // 读取门店模板配置
        getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
          let feeValue = feeForm.value
          initFeeDetail(feeValue, storeTemplate)
          // 更新费用模板 id
          priceTemplateId.value = templateId
        })
      })
    }
  }
  // 关闭
  const close = () => {
    feeForm.value = {
      randomKey: 0,
      orderFee: [
        {
          // 费用类型（线上费用|线下费用）
          feeType: 1,
          feeDetailList: [],
          priceTemplateId: priceTemplateId,
          feeDetailTypeList: ['addServiceFee', 'preferentialFee', 'otherFee'],
        },
      ],
    }
    visible.value = false
  }
  // 保存
  const handleBeforeOk = () => {
    close()
    emit('ok')
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  .page-container {
    max-height: calc(100vh - 210px);
  }
</style>
